package com.os.opencv.java.chapter8;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.util.LinkedList;
import java.util.List;

public class BackProject {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/gdl.jpg");
        Mat hsv = new Mat();
        Imgproc.cvtColor(src, hsv, Imgproc.COLOR_BGR2GRAY);
        HighGui.imshow("leaf", hsv);
        HighGui.waitKey(0);

        //将图像hue色调通道提取到hueList中
        Mat hue = new Mat(hsv.size(), hsv.depth());
        List<Mat> hsvList = new LinkedList<>();
        List<Mat> hueList = new LinkedList<>();
        hsvList.add(hsv);
        hueList.add(hue);
        Core.mixChannels(hsvList, hueList, new MatOfInt(0, 0));

        //直方图参数设置
        int bins = 25;
        int histSize = Math.max(bins, 2);
        float[] hueRange = {0, 180};

        //直方图数据统计并归一化
        Mat hist = new Mat();
        Imgproc.calcHist(hueList, new MatOfInt(0), new Mat(), hist, new MatOfInt(histSize), new MatOfFloat(hueRange));
        Core.normalize(hist, hist, 0, 255, Core.NORM_MINMAX);

        //计算反相投影并在屏幕上显示
        Mat backProject = new Mat();
        Imgproc.calcBackProject(hueList, new MatOfInt(0), hist, backProject, new MatOfFloat(hueRange), 1);
        HighGui.imshow("calcHist", backProject);
        HighGui.waitKey(0);
        System.exit(0);
    }
}
